﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using PSE.Deployment.SetupBase.Configuration;
using PSE.Deployment.SetupBase.Parameter;
using PSE.Deployment.Engine.CustomExceptions;
using PSE.Deployment.Engine.Interfaces;

namespace PSE.Deployment.SetupBase.Steps
{
    public class StartPackage : SetupStep<Configuration.Actions.InstallWcfService>
    {
        public bool Start { get; set; }

        public StartPackage(IStepGroup parent, Group group, Configuration.Actions.InstallWcfService action, Parameter.Enums.SetupMode setupMode, bool start)
            : base(parent, group, action, setupMode)
        {
            this.Id = this.Action.Id + "-StartPackage";
            this.Start = start;
            this.ResetProgress(Action.Services.Count);
            this.Description = "Verficação dos pacotes";
        }

        public override void Execute()
        {
            this.ResetProgress(Action.Services.Count);

            if (this.SetupMode == Parameter.Enums.SetupMode.Install ||
                this.SetupMode == Parameter.Enums.SetupMode.Uninstall)
            {
                StartStopPackages();
            }
        }

        public override void Undo()
        {

        }

        private void StartStopPackages()
        {
            foreach (WcfService service in Action.Services)
            {
                if (this.IsStopped())
                    return;

                string packageName = SetupMainFactory.GetInstance().Parameter.SetupConfiguration.SystemInfo.Id + "_" + service.ProcessName;

                this.IncrementProgress(packageName);

                StartStopPackage(service, service.ProcessName);

                StartStopPackage(service, packageName);
            }
        }

        private void StartStopPackage(WcfService service, string packageName)
        {
            if (Start)
            {
                PSE.Deployment.Util.WcfService.StartPackage(service.ServerName, packageName);
            }
            else
            {
                try
                {
                    PSE.Deployment.Util.WcfService.StopPackage(service.ServerName, packageName);
                }
                catch (Exception ex)
                {
                    SetupMainFactory.GetInstance().WriteStepLog(this, string.Format("Não foi possível parar o pacote {0} do servidor {1}", packageName, service.ServerName), ex);
                }
            }
        }
    }
}
